package com.gzhryc.net_marketing.cloud.business.services;

import java.sql.SQLException;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.time.DateUtils;

import com.gzhryc.common.event.DelayHandleService;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.jdbc.Conditions;
import com.gzhryc.jdbc.JdbcSession;
import com.gzhryc.jdbc.MultiDBTools;
import com.gzhryc.net_marketing.cloud.business.PayConfig;
import com.gzhryc.net_marketing.cloud.business.TradeNoUtils;
import com.gzhryc.net_marketing.cloud.business.dao.TeamPayApplyDao;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApply;
import com.gzhryc.net_marketing.cloud.business.dao.db.TeamPayApplyMember;
import com.gzhryc.net_marketing.cloud.business.dao.enums.TeamPayApplyEnum;
import com.gzhryc.net_marketing.cloud.business.dao.enums.TeamPayApplyMemberEnum;
import com.gzhryc.net_marketing.cloud.business.event.TeamPayApplySettlementEvent;
import com.gzhryc.net_marketing.cloud.business.services.dto.TeamPayApplySearch;
import com.gzhryc.net_marketing.cloud.goods.dao.db.Goods;
import com.gzhryc.net_marketing.cloud.goods.dao.db.GoodsSpace;
import com.gzhryc.net_marketing.cloud.goods.dao.enums.GoodsEnum;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsService;
import com.gzhryc.net_marketing.cloud.goods.services.GoodsSpaceService;
import com.gzhryc.net_marketing.cloud.logistics.LogisticsCostUtils;
import com.gzhryc.pay.adaptation.weixin.WXPayNormalPayService;
import com.gzhryc.shared_device.base.ILogisticsCostConfig;
import com.gzhryc.shared_device.base.models.OperateInfo;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WXRefundOrder;
import com.gzhryc.shared_device.common.payment.dao.db.WalletPayOrder;
import com.gzhryc.shared_device.oem.code.member.dao.db.Member;

public class TeamPayApplyService {

	static Logger log = Logger.getLogger(TeamPayApplyService.class);

	public static TeamPayApplyService self() {
		return MultiDBTools.getService(TeamPayApplyService.class, true);
	}

	public static TeamPayApplyService self(String jdbcKey) {
		return MultiDBTools.getService(jdbcKey, TeamPayApplyService.class, true);
	}

	TeamPayApplyDao dao;

	public TeamPayApplyService(String jdbcKey) {
		dao = new TeamPayApplyDao(jdbcKey);
	}

	public List<TeamPayApply> findBySearch(TeamPayApplySearch search, Integer pageNo, Integer pageLimit) {
		Conditions condition = dao.buildConditions(search);
		condition.desc("createDate");
		try {
			return dao.findByCondition(condition, pageNo, pageLimit);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	public Long countBySearch(TeamPayApplySearch search) {
		Conditions condition = dao.buildConditions(search);
		try {
			return dao.count(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return 0L;
	}

	public List<TeamPayApply> findByIds(List<Long> ids){
		Conditions conditions = new Conditions(TeamPayApply.class);
		conditions.and().is("id",ids);

		try {
			return dao.findByCondition(conditions);
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}

	public List<TeamPayApply> findExpireByDate(Date endDate, Integer pageNo, Integer pageLimit) {
		Conditions condition = new Conditions(TeamPayApply.class);
		condition.and().is("state", TeamPayApplyEnum.State.Opening.index());
		condition.and().le("endDate", endDate);

		try {
			return dao.findByCondition(condition, pageNo, pageLimit);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 查询等待支付超时
	 * @param endDate
	 * @param pageNo
	 * @param pageLimit
	 * @return
	 */
	public List<TeamPayApply> findWaitPayExpireByDate(Date endDate, Integer pageNo, Integer pageLimit) {
		Conditions condition = new Conditions(TeamPayApply.class);
		condition.and().is("state", TeamPayApplyEnum.State.Initiating.index());
		condition.and().le("endDate", endDate);

		try {
			return dao.findByCondition(condition, pageNo, pageLimit);
		} catch (SQLException e) {
			log.error(e.getMessage(), e);
		}
		return null;
	}

	public TeamPayApply getById(Long id) {
		if (id != null) {
			try {
				return dao.getById(id);
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
		return null;
	}

	public TeamPayApply getByNew() {
		Conditions condition = new Conditions(TeamPayApply.class);
		condition.and().is("state", TeamPayApplyEnum.State.Opening.index());
		condition.desc("createDate");
		try {
			return dao.get(condition);
		} catch (SQLException e) {
			log.error(e.getMessage(),e);
		}
		return null;
	}

	public TeamPayApply getJoinByGoodsIdAndMemberId(Long goodsId, Long memberId) {
		if (goodsId != null && memberId != null) {
			TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().getParticipatingByGoodsIdAndMemberId(goodsId, memberId);
			if (applyMember != null) {
				try {
					return dao.getJoinById(applyMember.getApplyId());
				} catch (SQLException e) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return null;
	}

	public TeamPayApplyMember apply(Member member, Long goodsId, Long goodsSpaceId, Integer goodsNum, PayConfig payConfig) throws LogicException {
		if (member != null && goodsId != null) {
			if(payConfig.getMailAddress() == null){
				throw new LogicException("收货地址不存在");
			}
			Goods goods = GoodsService.self().getById(goodsId);
			if (goods == null) {
				throw new LogicException("商品不存在");
			}
			if(GoodsEnum.State.OffTheShelf.index().equals(goods.getState())){
				throw new LogicException("商品已下架");
			}else if(GoodsEnum.State.NoInventory.index().equals(goods.getState())){
				throw new LogicException("商品暂无库存");
			}
			GoodsSpace goodsSpace = null;
			if(goodsSpaceId != null) {
				goodsSpace = GoodsSpaceService.self().getByKeys(goods.getId(), goodsSpaceId);
				if (goodsSpace == null) {
					throw new LogicException("商品的规格不存在");
				}
			}else if(GoodsSpaceService.self().countByGoodsId(goods.getId()) > 0){
				throw new LogicException("请选择购买商品的规格");
			}

			TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().getParticipatingByGoodsIdAndMemberId(goodsId, member.getId());
			if (applyMember != null) {
				TeamPayApply applyEntity = getById(applyMember.getApplyId());
				if (applyEntity != null) {
					if(TeamPayApplyEnum.State.Opening.index().equals(applyEntity.getState())) {
						throw new LogicException("已参加该商品团拼");
					}else if(TeamPayApplyEnum.State.Initiating.index().equals(applyEntity.getState())){
						throw new LogicException("有未支付的商品团拼订单，请优先使用");
					}
				}else {
					applyMember = null;
				}
			}

			applyMember = TeamPayApplyMemberService.self().getWaitingByGoodsIdAndMemberId(goodsId, member.getId());
			if (applyMember != null) {
				TeamPayApply applyEntity = getById(applyMember.getApplyId());
				if (applyEntity != null && TeamPayApplyEnum.State.Opening.index().equals(applyEntity.getState())) {
					return applyMember;
				}else {
					applyMember = null;
				}
			}

			Integer money = goods.getTeamPayMoney() * goodsNum;

			ILogisticsCostConfig logisticsCostConfig = LogisticsCostUtils.getUsableConfig(goods.getSupplierId()
					,payConfig.getLogisticsCompanyId(),payConfig.getMailAddress().getProvince());
			Integer logisticsMoney = 0;
			if (logisticsCostConfig == null) {
				throw new LogicException("未找到物流价格配置");
			} else {
				boolean free = false;
				if (goods.getSupplierId() != null) {
					//使用批发价
					Integer wholesaleMoney = goods.getWholesaleMoney() * goodsNum;
					if (LogisticsCostUtils.isFree(logisticsCostConfig,wholesaleMoney)) {
						free = true;
					}
				} else if (LogisticsCostUtils.isFree(logisticsCostConfig,money)) {
					free = true;
				}
				if (free) {
					log.info("客单价触发免邮费，客单价：{{0}}，阀值：{{1}}", money, logisticsCostConfig.getFreeMinMoney());
				} else {
					logisticsMoney = logisticsCostConfig.getMoney();
					money = money + logisticsMoney;
				}
			}

			TeamPayApply applyEntity = new TeamPayApply();
			applyEntity.setMemberId(member.getId());
			applyEntity.setMemberNickname(member.getNickname());
			applyEntity.setMemberPhone(member.getPhone());
			applyEntity.setGoodsId(goods.getId());
			applyEntity.setGoodsName(goods.getName());
			applyEntity.setGoodsClassify(goods.getClassify());
			applyEntity.setGoodsTypeCodes(goods.getTypeCodes());
			applyEntity.setGoodsTypeNames(goods.getTypeNames());
			applyEntity.setGoodsImg(goods.getThumbnailImg());
			applyEntity.setGoodsMoney(goods.getPayMoney());
			applyEntity.setTeamMemberTotal(goods.getTeamCount());
			applyEntity.setTeamGainCount(goods.getGainCount());
			applyEntity.setTeamMemberCount(1);
			applyEntity.setTeamPayMoney(goods.getTeamPayMoney());
			applyEntity.setState(TeamPayApplyEnum.State.Initiating.index());
			applyEntity.setCreateDate(new Date());
			applyEntity.setEndDate(DateUtils.addMinutes(applyEntity.getCreateDate(), goods.getTeamMinute()));

			JdbcSession.begin();
			try {
				if (dao.insert(applyEntity) > 0) {
					applyMember = new TeamPayApplyMember();
					applyMember.setApplyId(applyEntity.getId());
					applyMember.setBusinessTradeNo(TradeNoUtils.createTradeNo());
					applyMember.setMemberId(member.getId());
					applyMember.setMemberPhone(member.getPhone());
					applyMember.setMemberNickname(member.getNickname());
					applyMember.setMemberFaceImg(member.getFaceImg());
					applyMember.setRoleType(TeamPayApplyMemberEnum.RoleType.Commander.index());
					applyMember.setGoodsId(applyEntity.getGoodsId());
					applyMember.setGoodsName(goods.getName());
					applyMember.setGoodsClassify(goods.getClassify());
					applyMember.setGoodsTypeCodes(goods.getTypeCodes());
					applyMember.setGoodsTypeNames(goods.getTypeNames());
					applyMember.setGoodsImg(goods.getThumbnailImg());
					applyMember.setGoodsMoney(goods.getPayMoney());
					applyMember.setGoodsCount(goodsNum);
					if(goodsSpace != null) {
						applyMember.setGoodsSpaceId(goodsSpace.getId());
						applyMember.setGoodsSpaceName(goodsSpace.getName());
					}
					applyMember.setPriority(1);
					applyMember.setLogisticsMoney(logisticsMoney);	//物流费用
					applyMember.setPayMoney(money);
					applyMember.setPayType(payConfig.getPayType());
					applyMember.setPayState(TeamPayApplyMemberEnum.PayState.Waiting.index());
					applyMember.setState(TeamPayApplyMemberEnum.State.Waiting.index());
					applyMember.setMailAddressId(payConfig.getMailAddress().getId());
					applyMember.setReceiveName(payConfig.getMailAddress().getReceiveName());
					applyMember.setReceivePhone(payConfig.getMailAddress().getReceivePhone());
					applyMember.setReceiveProvince(payConfig.getMailAddress().getProvince());
					applyMember.setReceiveAddress(payConfig.getMailAddress().getFullAddress());
					applyMember.setCreateDate(new Date());
					//物流信息
					applyMember.setLogisticsCompanyId(logisticsCostConfig.getCompanyId());
					applyMember.setLogisticsCompany(logisticsCostConfig.getCompanyName());

					if (TeamPayApplyMemberService.self().add(applyMember)) {
						JdbcSession.commit();
						return applyMember;
					}
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			} finally {
				JdbcSession.end();
			}

		}
		return null;
	}

	public TeamPayApplyMember join(Member member, Long applyId, Long goodsSpaceId, Integer goodsNum, PayConfig payConfig) throws LogicException {
		if (member != null && applyId != null && goodsNum != null) {
			if (payConfig.getMailAddress() == null) {
				throw new LogicException("收货地址不存在");
			}
			TeamPayApply applyEntity = getById(applyId);
			if (applyEntity == null) {
				throw new LogicException("团拼信息不存在");
			}

			if (TeamPayApplyEnum.State.Initiating.index().equals(applyEntity.getState())) {
				throw new LogicException("团拼未开始");
			} else if (!TeamPayApplyEnum.State.Opening.index().equals(applyEntity.getState())) {
				throw new LogicException("团拼已结束");
			}

			Goods goods = GoodsService.self().getById(applyEntity.getGoodsId());
			if (goods == null) {
				throw new LogicException("商品不存在");
			}
			if (GoodsEnum.State.OffTheShelf.index().equals(goods.getState())) {
				throw new LogicException("商品已下架");
			} else if (GoodsEnum.State.NoInventory.index().equals(goods.getState())) {
				throw new LogicException("商品暂无库存");
			}
			GoodsSpace goodsSpace = null;
			if (goodsSpaceId != null) {
				goodsSpace = GoodsSpaceService.self().getByKeys(goods.getId(), goodsSpaceId);
				if (goodsSpace == null) {
					throw new LogicException("商品的规格不存在");
				}
			} else if (GoodsSpaceService.self().countByGoodsId(goods.getId()) > 0) {
				throw new LogicException("请选择购买商品的规格");
			}

			TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().getByApplyIdAndMemberId(applyId, member.getId());
			if (applyMember != null) {
				if (TeamPayApplyMemberEnum.State.Participating.index().equals(applyMember.getState())) {
					throw new LogicException("你已经申请了该团拼");
				} else if (TeamPayApplyMemberEnum.PayState.Waiting.index().equals(applyMember.getPayState())) {
					throw new LogicException("你已申请，请优先支付已申请团拼");
				} else {
					throw new LogicException("你申请的团拼信息异常，请联系客服");
				}
			}

			Integer money = applyEntity.getTeamPayMoney() * goodsNum;

			ILogisticsCostConfig logisticsCostConfig = LogisticsCostUtils.getUsableConfig(goods.getSupplierId()
					, payConfig.getLogisticsCompanyId(), payConfig.getMailAddress().getProvince());
			Integer logisticsMoney = 0;
			if (logisticsCostConfig == null) {
				throw new LogicException("未找到物流价格配置，请联系客服");
			} else {
				boolean free = false;
				if (goods.getSupplierId() != null) {
					//使用批发价
					Integer wholesaleMoney = goods.getWholesaleMoney() * goodsNum;
					if (LogisticsCostUtils.isFree(logisticsCostConfig,wholesaleMoney)) {
						free = true;
					}
				} else if (LogisticsCostUtils.isFree(logisticsCostConfig,money)) {
					free = true;
				}
				if (free) {
					log.info("客单价触发免邮费，客单价：{{0}}，阀值：{{1}}", money, logisticsCostConfig.getFreeMinMoney());
				} else {
					logisticsMoney = logisticsCostConfig.getMoney();
					money = money + logisticsMoney;
				}
			}

			Integer priority = applyEntity.getTeamMemberCount() + 1;

			JdbcSession.begin();
			try {
				applyMember = new TeamPayApplyMember();
				applyMember.setApplyId(applyEntity.getId());
				applyMember.setBusinessTradeNo(TradeNoUtils.createTradeNo());
				applyMember.setMemberId(member.getId());
				applyMember.setMemberFaceImg(member.getFaceImg());
				applyMember.setMemberNickname(member.getNickname());
				applyMember.setMemberPhone(member.getPhone());
				applyMember.setRoleType(TeamPayApplyMemberEnum.RoleType.LeagueMember.index());
				applyMember.setGoodsId(goods.getId());
				applyMember.setGoodsName(goods.getName());
				applyMember.setGoodsImg(goods.getThumbnailImg());
				applyMember.setGoodsClassify(goods.getClassify());
				applyMember.setGoodsTypeCodes(goods.getTypeCodes());
				applyMember.setGoodsTypeNames(goods.getTypeNames());
				applyMember.setGoodsCount(goodsNum);
				if (goodsSpace != null) {
					applyMember.setGoodsSpaceId(goodsSpace.getId());
					applyMember.setGoodsSpaceName(goodsSpace.getName());
				}
				applyMember.setPriority(priority);
				applyMember.setLogisticsMoney(logisticsMoney);
				applyMember.setPayMoney(money);
				applyMember.setPayType(payConfig.getPayType());
				applyMember.setPayState(TeamPayApplyMemberEnum.PayState.Waiting.index());
				applyMember.setState(TeamPayApplyMemberEnum.State.Waiting.index());
				applyMember.setMailAddressId(payConfig.getMailAddress().getId());
				applyMember.setReceiveName(payConfig.getMailAddress().getReceiveName());
				applyMember.setReceivePhone(payConfig.getMailAddress().getReceivePhone());
				applyMember.setReceiveProvince(payConfig.getMailAddress().getProvince());
				applyMember.setReceiveAddress(payConfig.getMailAddress().getFullAddress());
				applyMember.setCreateDate(new Date());

				//物流信息
				applyMember.setLogisticsCompanyId(logisticsCostConfig.getCompanyId());
				applyMember.setLogisticsCompany(logisticsCostConfig.getCompanyName());

				if (TeamPayApplyMemberService.self().add(applyMember)) {
					JdbcSession.commit();
					return applyMember;
				}
			} catch (Exception e) {
				log.error(e.getMessage(), e);
			} finally {
				JdbcSession.end();
			}
		}
		return null;
	}

	public boolean closeApply(TeamPayApply simpleTeamPayApply) throws LogicException {
		if(simpleTeamPayApply != null) {
			if (!TeamPayApplyEnum.State.Initiating.index().equals(simpleTeamPayApply.getState())) {
				throw new LogicException(simpleTeamPayApply.getStateName() + "的拼团无法关闭");
			}

			Conditions conditions = new Conditions(TeamPayApply.class);
			conditions.and().is("id",simpleTeamPayApply.getId());
			conditions.and().is("state", TeamPayApplyEnum.State.Initiating.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.Close.index());

			try {
				return dao.updateNotNull(updateEntity,conditions) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return false;
	}

	/**
	 * 增加参与会员并检查是否完成
	 * @return
	 */
	public boolean payResult(WXPayOrder payOrder,OperateInfo operateInfo) {
		TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().payResult(payOrder,operateInfo);
		if (applyMember != null) {
			TeamPayApply apply = getById(applyMember.getApplyId());
			if (apply != null) {
				if (TeamPayApplyEnum.State.Initiating.index().equals(apply.getState())) {
					if (applyMember.getMemberId().equals(apply.getMemberId())) {
						if(TeamPayApplyMemberEnum.PayState.Success.index().equals(applyMember.getPayState())){
							TeamPayApply updateEntity = new TeamPayApply();
							updateEntity.setId(apply.getId());
							updateEntity.setState(TeamPayApplyEnum.State.Opening.index());
							try {
								if (dao.updateNotNull(updateEntity) > 0) {
									return true;
								}
							} catch (SQLException e) {
								log.error(e.getMessage(), e);
							}
						}
					} else {
						log.error("团拼发起人与支付人不一致，团拼用户：{{0:json}}，团拼信息：{{1:json}}", applyMember, apply);
					}
				} else if (TeamPayApplyEnum.State.Opening.index().equals(apply.getState())) {
					if(TeamPayApplyMemberEnum.PayState.Success.index().equals(applyMember.getPayState())) {
						TeamPayApply updateEntity = new TeamPayApply();
						updateEntity.setId(apply.getId());
						updateEntity.setTeamMemberCount(apply.getTeamMemberCount() + 1);
						if (updateEntity.getTeamMemberCount() >= apply.getTeamMemberTotal()) {
							updateEntity.setState(TeamPayApplyEnum.State.WaitSettlement.index());
						}
						try {
							if (dao.updateNotNull(updateEntity) > 0) {
								apply.setTeamMemberCount(updateEntity.getTeamMemberCount());
								apply.setState(updateEntity.getState());
								if (updateEntity.getState() != null && TeamPayApplyEnum.State.WaitSettlement.index().equals(updateEntity.getState())) {
									TeamPayApplySettlementEvent event = new TeamPayApplySettlementEvent(apply);
									DelayHandleService.get().addEvent(event);
								}
								return true;
							}
						} catch (SQLException e) {
							log.error(e.getMessage(), e);
						}
					}
				} else {
					log.error("团拼状态错误，团拼信息：{{0:json}}", apply);
				}
			} else {
				log.error("未获取团拼信息，团拼用户：{{0:json}}", applyMember);
			}
		}
		return false;
	}
	
	public boolean payResult(WalletPayOrder payOrder,OperateInfo operateInfo) {
		TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().payResult(payOrder,operateInfo);
		if (applyMember != null) {
			TeamPayApply apply = getById(applyMember.getApplyId());
			if (apply != null) {
				if (TeamPayApplyEnum.State.Initiating.index().equals(apply.getState())) {
					if (applyMember.getMemberId().equals(apply.getMemberId())) {
						if(TeamPayApplyMemberEnum.PayState.Success.index().equals(applyMember.getPayState())){
							TeamPayApply updateEntity = new TeamPayApply();
							updateEntity.setId(apply.getId());
							updateEntity.setState(TeamPayApplyEnum.State.Opening.index());
							try {
								if (dao.updateNotNull(updateEntity) > 0) {
									return true;
								}
							} catch (SQLException e) {
								log.error(e.getMessage(), e);
							}
						}
					} else {
						log.error("团拼发起人与支付人不一致，团拼用户：{{0:json}}，团拼信息：{{1:json}}", applyMember, apply);
					}
				} else if (TeamPayApplyEnum.State.Opening.index().equals(apply.getState())) {
					if(TeamPayApplyMemberEnum.PayState.Success.index().equals(applyMember.getPayState())) {
						TeamPayApply updateEntity = new TeamPayApply();
						updateEntity.setId(apply.getId());
						updateEntity.setTeamMemberCount(apply.getTeamMemberCount() + 1);
						if (updateEntity.getTeamMemberCount() >= apply.getTeamMemberTotal()) {
							updateEntity.setState(TeamPayApplyEnum.State.WaitSettlement.index());
						}
						try {
							if (dao.updateNotNull(updateEntity) > 0) {
								apply.setTeamMemberCount(updateEntity.getTeamMemberCount());
								apply.setState(updateEntity.getState());
								if (updateEntity.getState() != null && TeamPayApplyEnum.State.WaitSettlement.index().equals(updateEntity.getState())) {
									TeamPayApplySettlementEvent event = new TeamPayApplySettlementEvent(apply);
									DelayHandleService.get().addEvent(event);
								}
								return true;
							}
						} catch (SQLException e) {
							log.error(e.getMessage(), e);
						}
					}
				} else {
					log.error("团拼状态错误，团拼信息：{{0:json}}", apply);
				}
			} else {
				log.error("未获取团拼信息，团拼用户：{{0:json}}", applyMember);
			}
		}
		return false;
	}

	public boolean refundResult(WXPayOrder payOrder, WXRefundOrder refundOrder){
		TeamPayApplyMember applyMember = TeamPayApplyMemberService.self().getByPayTradeNo(payOrder.getTradeNo());
		if(applyMember != null){
			applyMember = TeamPayApplyMemberService.self().refundResult(applyMember,refundOrder);

			TeamPayApply simpleTeamPayApply = this.getById(applyMember.getApplyId());
			if(simpleTeamPayApply != null){
				//TODO 不知道要干撒
				return true;
			}

		}
		return false;
	}

	public boolean toStartSettlement(Long id){
		if(id != null) {
			Conditions condition = new Conditions(TeamPayApply.class);
			condition.and().is("id", id);
			condition.and().is("state", TeamPayApplyEnum.State.WaitSettlement.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.StartSettlement.index());

			try {
				return dao.updateNotNull(updateEntity,condition) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return false;
	}

	public boolean toWaitSettlement(Long id){
		if(id != null) {
			Conditions condition = new Conditions(TeamPayApply.class);
			condition.and().is("id", id);
			condition.and().is("state", TeamPayApplyEnum.State.StartSettlement.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.WaitSettlement.index());

			try {
				return dao.updateNotNull(updateEntity,condition) > 0;
			} catch (SQLException e) {
				log.error(e.getMessage(),e);
			}
		}
		return false;
	}

	/**
	 * 结算
	 * @param apply
	 * @param memberList
	 * @return
	 */
	public boolean settlement(TeamPayApply apply, List<TeamPayApplyMember> memberList,OperateInfo operateInfo) {
		if (apply != null && memberList != null && memberList.size() > 0) {
			Conditions condition = new Conditions(TeamPayApply.class);
			condition.and().is("id", apply.getId());
			condition.and().is("state", TeamPayApplyEnum.State.StartSettlement.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.Finish.index());

			JdbcSession.begin();
			try {
				if (dao.updateNotNull(updateEntity, condition) > 0) {
					boolean isSuccess = false;
					for (TeamPayApplyMember applyMember : memberList) {
						if (TeamPayApplyMemberService.self().toFinish(apply,applyMember,operateInfo)) {
							isSuccess = true;
						} else {
							isSuccess = false;
							log.error("执行团拼成功失败，团拼会员信息：{{0:json}}", applyMember);
							break;
						}
					}

					if(isSuccess){
						JdbcSession.commit();
						return true;
					}
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			} finally {
				JdbcSession.end();
			}
		}
		return false;
	}

	/**
	 * 流拼
	 * @param applyEntity
	 * @return
	 */
	public boolean toDrain(TeamPayApply applyEntity,WXPayNormalPayService payService,OperateInfo operateInfo) {
		if (applyEntity != null && applyEntity.getId() != null) {
			if (TeamPayApplyEnum.State.Drain.index().equals(applyEntity.getState())) {
				return true;
			}

			Conditions condition = new Conditions(TeamPayApply.class);
			condition.and().is("id",applyEntity.getId());
			condition.and().is("state", TeamPayApplyEnum.State.Opening.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.Drain.index());

			try {
				if (dao.updateNotNull(updateEntity, condition) > 0) {
					List<TeamPayApplyMember> applyMemberList = TeamPayApplyMemberService.self().findByApplyId(applyEntity.getId());
					if(applyMemberList != null && applyMemberList.size() > 0){
						for(TeamPayApplyMember simpleTeamPayApplyMember : applyMemberList){
							if(!TeamPayApplyMemberService.self().toDrain(simpleTeamPayApplyMember,payService,operateInfo)){
								log.error("团拼流拼处理失败，参与者信息：{{0:json}}",simpleTeamPayApplyMember);
							}
						}
					}
					return true;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
		return false;
	}

	public boolean toClose(TeamPayApply applyEntity) {
		if (applyEntity != null && applyEntity.getId() != null) {
			if (TeamPayApplyEnum.State.Close.index().equals(applyEntity.getState())) {
				return true;
			}

			Conditions condition = new Conditions(TeamPayApply.class);
			condition.and().is("id",applyEntity.getId());
			condition.and().is("state", TeamPayApplyEnum.State.Initiating.index());

			TeamPayApply updateEntity = new TeamPayApply();
			updateEntity.setState(TeamPayApplyEnum.State.Close.index());

			try {
				if (dao.updateNotNull(updateEntity, condition) > 0) {
					List<TeamPayApplyMember> applyMemberList = TeamPayApplyMemberService.self().findByApplyId(applyEntity.getId());
					if(applyMemberList != null && applyMemberList.size() > 0){
						for(TeamPayApplyMember simpleTeamPayApplyMember : applyMemberList){
							if(!TeamPayApplyMemberService.self().toClose(simpleTeamPayApplyMember)){
								log.error("团拼关闭处理失败，参与者信息：{{0:json}}",simpleTeamPayApplyMember);
							}
						}
					}
					return true;
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			}
		}
		return false;
	}

	public boolean deleteById(Long id){
		if(id != null){
			JdbcSession.begin();
			try {
				if(dao.deleteById(id) > 0){
					if(TeamPayApplyMemberService.self().deleteByApplyId(id)) {
						JdbcSession.commit();
						return true;
					}
				}
			} catch (SQLException e) {
				log.error(e.getMessage(), e);
			} finally {
				JdbcSession.end();
			}
		}
		return false;
	}
}
